package appendonly

import (
	"archive/tar"
	"compress/gzip"
	"io"
	"os"
	"strings"
	"willow/command"
	"willow/common/sdk"
)

var pathAof  = "save/appendonly.aof"

var commandExclude = map[string]string{
	"get" 	: "get",
	"save" 	: "save",
	"getex" : "getex",
}

func SaveCommand(command string)  {
	temp := strings.Split(command," ")
	fileInfo, _ := os.Stat(pathAof)
	filesize:= fileInfo.Size()		//文件大小
	if filesize > 32*1024*1024 {
		Compress(pathAof)
	}
	if _,ok := commandExclude[temp[0]]; !ok {
		sdk.WriteFile(pathAof,command,os.O_WRONLY | os.O_CREATE | os.O_APPEND)
	}
}

func RestoreAof()  {
	commdSlice := sdk.ReadFile(pathAof)
	if commdSlice != nil {
		for i := 0; i < len(commdSlice); i++  {
			if commdSlice[i] != "" {
				tempCommd := strings.TrimSpace(commdSlice[i])
				command.Parameter(tempCommd,false)
			}
		}
	}
}


func Compress(strPath string) error {
	fw, err := os.Create("save/appendonly.tar.gz")
	if err != nil {
		return nil
	}
	defer fw.Close()
	gw := gzip.NewWriter(fw)
	defer gw.Close()
	tw := tar.NewWriter(gw)
	defer tw.Close()
	dir, err := os.Open(strPath)
	if err != nil {
		return nil
	}
	fi,err := dir.Stat()
	if err != nil {
		return nil
	}

	h := new(tar.Header)
	h.Name = fi.Name()
	h.Size = fi.Size()
	h.Mode = int64(fi.Mode())
	h.ModTime = fi.ModTime()

	err = tw.WriteHeader(h)
	if err != nil {
		return err
	}
	_, err = io.Copy(tw, dir)
	if err != nil {
		panic(err)
	}
	return nil
}
